<template>
    <div class="page">
        <Row class="margin-bottom-20 search" >
            <Col span="2">
                <span class="label">用户名：</span>
            </Col>
            <Col span="5">
                <Select v-model="args.search.userName" clearable filterable placeholder="请选择用户名" style="width:180px">
                    <Option v-for="item in searchTb" :value="item.key" :key="item.key">{{ item.label }}</Option>
                </Select>
            </Col>
            <Col span="2">
                <span class="label">员工状态：</span>
            </Col>
            <Col span="5">
                <Select v-model="args.search.status" clearable filterable placeholder="请选择员工状态" style="width:180px">
                    <Option v-for="item in employeeStatusOpts" :value="item.val" :key="item.val">{{ item.label }}</Option>
                </Select>
            </Col>
            <Col span="2">
                <span class="label">关联组织：</span>
            </Col>
            <Col span="5">
                <Select v-model="orgStructIdStatus" clearable filterable placeholder="请选择员工状态" style="width:180px">
                    <Option v-for="item in orgStructIdStatusOpts" :value="item.val" :key="item.val">{{ item.label }}</Option>
                </Select>
            </Col>
            <Col span="2">
                <Button v-show="hasButtonPermission('101010401')" type="primary" @click="pageIndexChange(1)">查询</Button>
            </Col>
        </Row>
        <Row class="margin-bottom-20">
            <Col span="4" offset="1">
                <Button v-show="hasButtonPermission('101010409')" type="ghost" @click.prevent="setRelativeEmployee"><Icon type="person" class="margin-right-8"></Icon>设置对应人员</Button>
                <SetRelativeEmployee @employeeSelected="employeeSelected"></SetRelativeEmployee>
            </Col>
            <Col span="12">
                <Button v-show="hasButtonPermission('101010402')"  type="ghost" @click="employeeInfo={};showEditEmployeeModal=true;emAdd()" class="margin-left-15"><Icon type="person-add" class="margin-right-8"></Icon>新增员工</Button>
                <EmployeeEdit :showModal="showEditEmployeeModal"  @toggleModal="toggleModal" :mode="mode" :employeeInfo="employeeInfo"></EmployeeEdit>
                <SetRoles @rolesSelected="rolesSelected"></SetRoles>
            </Col>
        </Row>
        <Row  :gutter="10">
            <Col span="5" style="max-height: 900px;overflow-x: hidden ;overflow-y: scroll;margin-top: 8px;border: 1px solid #ccc">
                <Tree :data="orgStructTree" :render="renderTree"></Tree>
            </Col>
            <Col span="19">
                <Table ref="employeeTb" style="margin: 8px 0" border :columns="employees_columns" :data="employees_data" @on-selection-change="selectionChange"></Table>
                <Page :total="employeeTbPage.total" :page-size="args.limit" :current="employeeTbPage.current" size="small" show-elevator show-sizer @on-change="pageIndexChange" @on-page-size-change="pageSizeChange"></Page>
            </Col>
        </Row>
    </div>
</template>

<script type="text/ecmascript-6">
    import EmployeeEdit from './EmployeeEdit.vue'
    import SetRelativeEmployee from './setRelativeEmployee.vue'
    import SetRoles from './setRoles.vue'
    import * as employeeOpr from '../../http/employee.api'
    import * as orgStructOpr from '../../http/orgStruct.api'
    import moment from 'moment'

    export default {
        data () {
            return {
                mode:'add',// 模式,新增和编辑模式
                showEditEmployeeModal: false, // 编辑员工弹框开关
                showRelativeEmployeeModal: false, // 设置关联 人员开关

                employeeTbSelection: [],  // 已选择 的员工
                employeeInfo: {},       // 编辑操作人员 ， 新增传 空对象
                searchTb: [],
                employeeTbPage: {
                    current: 1,
                    total: 200,
                },
                orgStructIdStatus: '',
                orgStructIdStatusOpts: [
                    {label: '全部', val: ''},
                    {label: '有组织', val: '-1'},
                    {label: '无组织', val: '0'},
                ],
                args: { // 员工列表参数
                    search: {
                        userName: '',     //用户名
                        employeeName: '', // 员工姓名
                        status: undefined,       //员工状态
                        orgStructId: undefined,  //组织架构id
                    },
                    pageReqired: true,    // 分页 true 是 false 否
                    limit: 20,            // 每页数目
                    offset: 0,            // 偏移量
                    sort: 'id',   // 排序的字段
                    order: 'desc',        // asc 升序 desc 降序
                },
                employeeStatusOpts: [
                    {label: '正常', val: 'normal'},
                    {label: '禁用', val: 'forbidden'},
                    {label: '离职', val: 'disable'}
                ],
                orgStructTree: [{
                    title: '总经办',
                    expand: true,
                    origin: {id: 0, status: true},
                    children: []
                }],
                buttonProps: {
                    type: 'ghost',
                    size: 'small',
                },
                employees_columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center',
                        fixed: 'left'
                    }, {
                        title: '用户名',
                        key: 'userName',
                        width: 100,
                        fixed: 'left',
                        sortable: true
                    }, {
                        title: '员工姓名',
                        key: 'employeeName',
                        width: 140
                    }, {
                        title: '性别',
                        key: 'genderDesc',
                        width: 75
                    }, {
                        title: '部门',
                        key: 'deptName',
                        width: 100
                    }, {
                        title: '职能',
                        key: 'duty',
                        width: 150
                    }, {
                        title: '关联角色',
                        key: 'roleNames',
                        width: 150
                    }, {
                        title: '状态',
                        key: 'status',
                        width: 75,
                        render: function (h, {row, index, column}) {
                            const _self = this;
                            let node = _self.employeeStatusOpts.find(item => item.val===row[column.key]);
                            return h('span',{style:{color: (row[column.key]==='normal')&&'#008000'||(row[column.key]==='forbidden')&&'#FF0000'}},[node&&node.label||'']);
                        }.bind(this),
                    }, {
                        title: '联系方式',
                        key: 'contact',
                        width: 120
                    }, {
                        title: '腾讯通',
                        key: 'rtx',
                        width: 100
                    }, {
                        title: '创建时间',
                        key: 'createTime',
                        width: 100,
                        render: (h, {row, index, column}) => h('span',{},[(row[column.key]&&moment(row[column.key]).format('YYYY-MM-DDTHH:mm:ss')||'')]),
                    }, {
                        title: '最后登录时间',
                        key: 'entryTime',
                        width: 100,
                        render: (h, {row, index, column}) => h('span',{},[(row[column.key]&&moment(row[column.key]).format('YYYY-MM-DDTHH:mm:ss')||'')]),
                    }, {
                        title: '操作',
                        // key: 'action',
                        // fixed: 'right',
                        width: 150,
                        render: (h, {row, index, column}) => {
                            const _this = this;
                            return h('div', [
                                _this.hasButtonPermission('101010407') && h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '8px'
                                    },
                                    on: { // 编辑用户
                                        click: function () {
                                            // 传递数据进 编辑框
                                            _this.employeeTbSelection = [JSON.parse(JSON.stringify(row))];
                                            _this.$store.commit('employee/setSelectedEmployee', _this.employeeTbSelection)

                                            // 弹出设置 关联人员的弹框
                                            _this.$store.commit('employee/toggleRelativeRolesModal', true)
                                        }
                                    }
                                }, '设置角色')||'',
                                _this.hasButtonPermission('101010404') && h('Button', {
                                    props: _this.buttonProps,
                                    on: { // 编辑用户
                                        click: function () {
                                            _this.mode = 'edit'
                                            console.log("此时的状态", _this.mode)
                                            // 传递数据进 编辑框
                                            _this.employeeInfo = row;
                                            _this.showEditEmployeeModal = true;
                                        }
                                    }
                                }, '编辑')||''
                            ]);
                        }
                    }
                ],
                employees_data: [],
            }
        },
        mounted() {
            this.getEmployees(); // 初始化列表
            this.getOrgStructList(); // 初始化组织架构树
            this.getEmployeeNames();
            // console.log('mode=', this.mode);
        },
        computed: {
            selNode: {  // 已选中 的组织架构 节点
                get() {
                    return this.$store.state.employee.selectedOrgStruct
                },
                set(value) {
                    this.$store.commit('employee/setSelectedOrgStruct', value)
                }
            },
        },
        watch: {
            orgStructIdStatus: function (newVal, oldVal) {
                this.selNode = null;  // 员工状态 用来筛选所有的 员工，主要是 未关联组织的员工
                // this.getEmployees();
            },
        },
        methods: {
            emAdd(){
                this.mode = 'add'
            },
            hasButtonPermission(permission) {
                return this.$store.getters['login/hasButtonPermission'](permission);
            },
            setRelativeEmployee() {
                const _this = this;
                if (!_this.selNode) {
                    return _this.$Message.warning('请先选择组织架构');
                }
                _this.$store.commit('employee/toggleRelativeEmployeeModal', true)
            },
            rolesSelected(nodes) {
                const _this = this;
                // 处理数据得到 roleIds
                // 调用接口
                employeeOpr.setRoles(_this.employeeTbSelection[0].id, {roleIds: nodes.map(role => role.origin.id)}).then(function (res) {
                    // console.log(res);
                    _this.$Message.success('关联角色成功');
                    _this.getEmployees();
                }).catch(function (err) {
                    console.log(err);
                });
            },
            employeeSelected(records) { // 设置关联人员
                const _this = this;
                // 处理数据得到 roleIds

                // 调用接口
                employeeOpr.batchUpdate({ids: records.map(item => item.id), orgStructId: _this.selNode.node.origin.id}).then(function (res) {
                    // console.log(res.data);
                    _this.$Message.success('批量设置关联人员成功');
                    _this.getEmployees();
                }).catch(function (err) {
                    console.log(err);
                });
            },
            toggleModal(show) {
                // console.log(show)
                this.showEditEmployeeModal = show;
                this.getEmployeeNames();
                this.getEmployees();
            },
            pageIndexChange(index) {
                this.args.offset = this.args.limit * (index - 1);
                this.employeeTbPage.current = index;
                this.getEmployees();
            },
            pageSizeChange(size) {
                this.args.limit = size;
                this.args.offset = 0;
                this.employeeTbPage.current = 1; // 此时改变当前页会触发 pageIndexChange 查询
                this.getEmployees();
            },
            renderTree (h, { root, node, data }) {
                const _this = this;
                let opr1 = [
                    _this.hasButtonPermission('101010403') && h('Button', {
                        props: { ...this.buttonProps, ...{ icon: 'ios-plus-empty', type: 'primary'}},
                        on: {
                            click: () => { this.addOrgStruct(root, node, data) }
                        }
                    })||''
                ];
                let opr2 = [
                    h('ButtonGroup', {}, [
                        _this.hasButtonPermission('101010403') && h('Button', {
                            props: { ...this.buttonProps, ...{ icon: 'ios-plus-empty'}},
                            on: {
                                click: () => { this.addOrgStruct(root, node, data) }
                            }
                        }),
                        _this.hasButtonPermission('101010405') && h('Button', {
                            props: { ...this.buttonProps, ...{ icon: 'edit'}},
                            on: {
                                click: () => { this.editOrgStruct(root, node, data) }
                            }
                        }),
                        _this.hasButtonPermission('101010410') && h('Button', {
                            props: { ...this.buttonProps, ...{ icon: 'ios-minus-empty'}},
                            on: {
                                click: () => { this.removeOrgStruct(root, node, data) }
                            }
                        })
                    ])];
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%',
                        lineHeight: '24px',
                        height: '24px'
                    }
                }, [
                    h('span', {
                        on: {
                            click: function() {
                                // console.log(root, node, data)
                                _this.selNode = (_this.selNode === node) ? null: node;
                                _this.args.search.orgStructId = _this.selNode ? _this.selNode.node.origin.id : null;
                                _this.getEmployees();
                            }
                        }}, [
                        h('Icon', {
                            props: { type: (data.children&&data.children.length)&&'ios-folder-outline'||'ios-paper-outline' },
                            style: { marginRight: '8px' }
                        }),
                        h('span',{class: { 'ivu-tree-title': true, 'ivu-tree-title-selected': _this.selNode === node }},
                            !data.origin.status ? [h('Badge',{props: {dot: true}}, [h('span',{on:{ mouseover: () => _this.$Message.warning(`${data.title} 被禁用`) }}, data.title)])] : data.title)
                    ]),
                    h('span', { style: { display: (_this.selNode === node)&&'inline-block'||'none', marginLeft: '5px' } }, (data.origin.id===0)&&opr1||opr2)
                ]);
            },
            addOrgStruct (root, node, data) { // 新增 部门
                const _self = this;
                let parentNode = node;
                let arr = [data.title];
                while(parentNode = root.find(el => el.nodeKey === parentNode.parent)) {
                    arr.unshift(parentNode.node.title);
                }
                const args = {
                    "dept": "", // 部门
                    "parentId": data.origin.id, // 当前组织id
                    "status": "normal" // 状态 normal正常 forbidden禁用
                };
                let tips = `当前操作提示：${arr.join(' | ')} 添加下级`
                _self.editOrgStructModal(args, tips, (args) => {
                    if (!args.dept) {
                        return _self.$Message.warning('请输入机构名称');
                    }
                    // 调用 添加接口
                    orgStructOpr.add({...args, ...{status: (args.status==='normal')}}).then(function (res) {
                        // 刷新
                        _self.getOrgStructList();
                    });
                })
            },
            editOrgStructModal(args, tips, okFn) {
                const _self = this;
                _self.$Modal.confirm({
                    title: '新增/编辑部门',
                    render: (h) => {
                        return h('div', {
                            style: {
                                // marginTop: '30px'
                            },
                        }, [
                            h('div', {
                                style: {
                                    marginTop: '15px',
                                    color: 'red'
                                },
                                props: {
                                },
                            },[tips]),
                            h('Input', {
                                style: {
                                    marginTop: '15px'
                                },
                                props: {
                                    value: args.dept,
                                    autofocus: true,
                                    placeholder: '请输入下级机构.'
                                },
                                on: {
                                    input: (val) => {
                                        args.dept = val;
                                    }
                                }
                            }),
                            h('Select', {
                                style: {
                                    marginTop: '15px'
                                },
                                props: {
                                    value: args.status,
                                    autofocus: true,
                                    placeholder: '请选择状态'
                                },
                                on: {
                                    'on-change': (val) => {
                                        args.status = val;
                                    }
                                }
                            }, [
                                h('Option', {
                                    props: { value: 'normal', label: '正常'},
                                }),
                                h('Option', {
                                    props: { value: 'forbidden', label: '禁用'},
                                })
                            ])
                        ])
                    },
                    okText: '保存',
                    onOk: () => {okFn(args)},
                    onCancel: () => {}
                })
            },
            editOrgStruct (root, node, data){
                const _self = this;
                let parentNode = node;
                let arr = [data.title];
                while(parentNode = root.find(el => el.nodeKey === parentNode.parent)) {
                    arr.unshift(parentNode.node.title);
                }

                const args = {
                    "dept": data.origin.dept, // 部门
                    "parentId": data.origin.parentId, // 当前组织id
                    "status": data.origin.status&&"normal"||'forbidden' // 状态 normal正常 forbidden禁用
                };
                let tips = `当前操作提示：${arr.join(' | ')} 编辑`
                // 查询 当前节点信息
                // orgStructOpr.getOrgStructDetail(data.origin.id).then(function (res) {
                    // console.log(res.data.result)
                    _self.editOrgStructModal({...args, ...{status: (args.status&&'normal'||'forbidden')}}, tips, (args) => {
                        if (!args.dept) {
                            return _self.$Message.warning('请输入机构名称');
                        }
                        // 调用 添加接口
                        orgStructOpr.update(data.origin.id, {...args, ...{status: (args.status==='normal')}}).then(function (res) {
                            // 刷新
                            _self.getOrgStructList();
                        });
                    })
                // })
            },
            removeOrgStruct (root, node, data) {
                const _self = this;
                let str = node.children&&node.children.length ? `当前节点含有 ${node.children&&node.children.length||0} 个子节点` : '';
                _self.$Modal.confirm({
                    title: '删除确认',
                    content: `<div><p>${str}</p>
                                <p>确定删除吗？</p>
                            </div>`,
                    onOk: () => {
                        const parentKey = root.find(el => el === node).parent;
                        const parent = root.find(el => el.nodeKey === parentKey).node;
                        if (_self.employees_data&&_self.employees_data.length) {
                            return _self.$Message.error('组织架构不能删除, 还有关联的员工');
                        }
                        // 删除 组织机构节点
                        orgStructOpr.delOrgStruct(data.origin.id).then(function (res) {
                            const index = parent.children.indexOf(data);
                            parent.children.splice(index, 1);
                            _self.$Message.info('删除成功');
                            // 清空选中节点
                            _self.selNode = null;
                        }).catch(function (err) {
                            _self.$Message.error(err.data.message);
                        });
                    },
                    onCancel: () => {
                        _self.$Message.info('取消');
                    }
                });
            },
            getEmployees() { // 获取 员工列表
                const _this = this;
                _this.args.search.userName = _this.args.search.userName|| undefined
                _this.args.search.employeeName = _this.args.search.employeeName|| undefined
                _this.args.search.status = _this.args.search.status|| undefined
                if (!_this.selNode) {
                    if (_this.orgStructIdStatus === '0') {
                        _this.args.search.orgStructId = 0
                    } else if (_this.orgStructIdStatus === '-1') {
                        _this.args.search.orgStructId = -1
                    } else {
                        _this.args.search.orgStructId = undefined
                    }
                } else {
                    _this.args.search.orgStructId = _this.args.search.orgStructId|| undefined
                }
                employeeOpr.getEmployees(_this.args).then(function (res) {
                    res.data&&res.data.rows&&res.data.rows.map(item => {
                        item.genderDesc = item.gender&&'男'||'女'
                        // 关联角色
                        item.roleNames = item.roles&&item.roles.map(role => role.roleName).join(',');
                        // 职能
                        item.duty = item.orgFuncs&&item.orgFuncs.map(duty => duty.funcName).join(',');
                        // 部门
                        item.deptName = item.orgStruct&&item.orgStruct.dept
                    });

                    _this.employees_data = res.data.rows;
                    // 设置分页信息
                    _this.employeeTbPage.total = res.data.total;
                }).catch(function () {
                    console.log(arguments);
                });
            },
            getOrgStructList() { // 获取所有组织架构
                const _this = this;
                orgStructOpr.getOrgStructList().then(function (res) {
                    let rootNode = res.data.result.find(item => item.parentId === 0); // 找根节点，可能调整
                    let groupsObj = res.data.result.reduce(function(groups, item) {
                        let val = (''+item['parentId']).toUpperCase();
                        groups[val] = groups[val] || [];
                        groups[val].push(item);
                        return groups;
                    }, {});
                    function buildTree(node) {
                        let obj = {
                            title: node.dept,
                            expand: true,
                            origin: node
                        };
                        if (groupsObj[node.id]) { // 有下级节点
                            // 设置子节点，进行监听
                            _this.$set(obj, 'children', groupsObj[node.id].map(item => buildTree(item)));
                        }
                        return obj;
                    }
                    _this.orgStructTree[0].children =  res.data.result.filter(item => item.parentId === 0).map(node => buildTree(node));
                }).catch(function () {
                    console.log(arguments);
                });
            },
            selectionChange(selection) {
                const _this = this;
                // console.log(selection)
                _this.employeeTbSelection = selection;
                _this.$store.commit('employee/setSelectedEmployee', selection)
            },
            getEmployeeNames(args) {
                const _this = this;
                employeeOpr.getEmployeeNames(args).then(function (res) {
                    const data = res.data.result;
                    _this.searchTb = Object.keys(data).map(key => ({key, label: `${key}-${data[key]||''}`}));
                }).catch(function (err) {
                    console.log(err)
                })
            },
        },
        components: {
            EmployeeEdit,
            SetRoles,
            SetRelativeEmployee
        }
    }
</script>
<style scoped>
    .search  .label {
        line-height: 32px;
        float: right;
    }
    .vertical-center-modal {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .vertical-center-modal .ivu-modal{
        top: 0;
    }
    .ivu-table-cell {
        padding: auto 10px !important;
    }
</style>
